//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.

#ifndef TACHOMETER_H
#define TACHOMETER_H
#include <QString>
#include <QByteArray>
#include <QLabel>
#include <QTextEdit>
#include <QTimer>
#include <QObject>
#include "cangateway.h"

/*
  Tachometer allows to transfer values of speed between two hosts.
  It works as a socket client that connects to a given host.

  The data packet is specified as follows:
  2 bytes for command (uint16)
  4 bytes for data (uint32)
  both in BigEndian notation.

  Command specific values are:
  '0' is a request to send back speed, data field is undefined
  '1' is a response, data field contains speed
  '3' is a request to set a mode,
      data field contains '0' for manual control or '1' for remote control

  Tachometer implements non-blocking sockets.
*/
class Tachometer : public QObject
{
    Q_OBJECT
private:
    QLabel *speedLabel;
    quint16 baseID;
    CanGateway * canGateway;

    enum Command {
        WriteSpeed = 1,
        ReadSpeed = 0,
        Mode = 3
    };

    struct Packet {
        quint16 command;
        quint32 data;
    } packetToRead, packetToWrite;

    static const quint32 packetSize = sizeof(quint16) + sizeof(quint32);
public:
    /* The tachometer is created with an established connection.
       The main widget is passed as parent, so that there's
       no need to worry about deleting the socket. */
    Tachometer(quint16 baseID, CanGateway * canGateway, QObject *parent = 0);

    /* sets a given speed that will be sent when the host requests */
    void setSpeed(qint8 speed);

    /* speedLabel (if set) is refreshed everytime when a new speed is received */
    void setSpeedLabel(QLabel *speedLabel);

    quint16 getBaseID();
private slots:
    void updateSpeed();
};

#endif // TACHOMETER_H
